package com.wanghaoran.mapper;

import com.wanghaoran.dto.RoomPageDTO;
import com.wanghaoran.entity.Room;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author wanghaoran
 */
@Repository
public interface RoomMapper {

    @Insert("""
            insert into rms_room
            (`title`, `address`, `info`, `capacity`, `version`, `deleted`, `created`, `updated`)
            values 
            (#{title}, #{address}, #{info}, #{capacity}, #{version}, #{deleted}, #{created}, #{updated})
            """)
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(Room room);

    @Select("""
            select * from rms_room t
            where t.id = #{param1} and t.deleted = 0
            """)
    Room select(Long id);

    @Select("""
            <script>
            select * from rms_room t
            <where>
                <if test='title != null'> title like concat('%', #{title}, '%') and </if>
                t.deleted = 0
            </where>
            </script>
            """)
    List<Room> list(RoomPageDTO dto);

    @Update("""
        <script>
        update rms_room
        <set>
            <if test ='title != null'> title = #{title}, </if>
            <if test ='address != null'> address = #{address}, </if>
            <if test ='info != null'> info = #{info}, </if>
            <if test ='capacity != null'> capacity = #{capacity}, </if>
            <if test ='deleted != null'> deleted = #{deleted}, </if>
            <if test ='created != null'> created = #{created}, </if>
            <if test ='updated != null'> updated = #{updated}, </if>
            version = version + 1
        </set>
        where id = #{id} and deleted = 0 and version = #{version}
        </script>
        """)
    int update(Room room);

    @Update("""
            update rms_room set deleted = 1, updated = current_timestamp where id = #{id}
            """)
    int delete(Long id);

    @Update("""
        <script>
        update rms_room set deleted = 1, updated = current_timestamp where 
        <foreach collection="list" item="e" open="id in (" close=")" separator=",">
            ${e}
        </foreach>
        </script>
        """)
    int deleteBatch(List<Long> ids);


}